package com.pphh.demo;

import com.pphh.demo.service.DemoService;

import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Please add description here.
 *
 * @author huangyinhuang
 * @date 2019/4/19
 */
@WebServlet(value = "/nioasync", asyncSupported = true)
public class NIOAsynServlet extends HttpServlet {

    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            100,
            200,
            600L,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(100));

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        AsyncContext asyncContext = request.startAsync();

        ServletInputStream inputStream = request.getInputStream();

        inputStream.setReadListener(new ReadListener() {

            @Override
            public void onDataAvailable() throws IOException {
            }

            @Override
            public void onAllDataRead() throws IOException {
                executor.execute(() -> {
                    String msg = DemoService.run(1);

                    try {
                        asyncContext.getResponse().getWriter().write("[non-blocking io + async servlet test] " + msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    asyncContext.complete();

                });
            }

            @Override
            public void onError(Throwable t) {
                asyncContext.complete();
            }
        });

    }

}
